﻿$import( "SmitearWebGL.Core.ResourceItem" );
$import( "SmitearWebGL.Resources.Shader" );

SmitearWebGL.Programs.AbstractProgram = SmitearWebGL.Core.ResourceItem.extend(
{
	/******** constructor ********/
	
	init : function()
	{
		this._super();
		this._registClass( "SmitearWebGL.Programs.AbstractProgram" );
		
		/******** private property ********/
		
		this._shader = null;
	}
	,
	
	/******** public method ********/
	
	getShader : function()
	{
		return this._shader;
	}
	,
	activeShader : function()
	{
		this.context.gl.useProgram( this._shader.glProgram );
		
		return SmitearWebGL.Core.HResult.SUCCESS;
	}
	,
	activeUniform : function( renderableObject )
	{
		return SmitearWebGL.Core.HResult.SUCCESS;
	}
	,
	activeMaterialUniform : function( renderableObject )
	{
		if ( ! renderableObject.getMaterial().doubleSide )
		{
			this.context.gl.enable( this.context.gl.CULL_FACE );
			this.context.gl.cullFace( this.context.gl.BACK );
		}
		else
			this.context.gl.disable( this.context.gl.CULL_FACE );
	}
	,
	generateShader : function( parameter )
	{
		if ( this._shader )
			return true;
		
		var vertexStr = this._generateVertexShaderStr( parameter );
		var fragmentStr = this._generateFragmentShaderStr( parameter );
		
		if ( vertexStr == "" || fragmentStr == "" )
			return false;

		var shader, shaderName = "";
		
		shaderName = "__shader_" + this.name + "__";
		shader = this.context.resourceManager.getResourceByName( shaderName );
		
		if ( ! shader )
		{
			shader = this.context.resourceManager.createResource( shaderName, SmitearWebGL.Resources.Shader );
			shader.loadVertexShaderFromString( vertexStr );
			shader.loadPixelShaderFromString( fragmentStr );
		}
		
		if ( shader.isProgramReady() )
		{
			this._shader = shader;
			if ( ! this._shader ) this._shader = shader;
		}
		else
		{
			shader.release();
			return false;
		}
		
		return true;
	}
	,
	
	/******** private method ********/
	
	_generateVertexShaderStr : function()
	{
	}
	,
	_generateFragmentShaderStr : function()
	{
	}
	,
	_createResource : function( params )
	{
		this._super();
		
		this._shader = null;
	}
	,
	_destroyResource : function()
	{
		this._super();
		
		if ( this._shader ) this._shader.release();
	}
}
);

/******** static property ********/

SmitearWebGL.Programs.AbstractProgram.Type =
{
	depth		: 0,
	normal		: 1,
	color		: 2,
	material	: 3,
	l_diff_a	: 4,
	l_diff_b	: 5,
	l_spec_a	: 6,
	l_spec_b	: 7,
	l_cCombine	: 8,
	l_ambient	: 9
}